package com.scorekeeper;

import java.util.ArrayList;

import com.scorekeeper.ui.StandingsListFragment;
import com.scorekeeper.ui.TeamViewFragment;
import com.scorekeeper.utils.Loader;

import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.app.ActionBar;
import android.content.Context;

public class StandingsActivity 
	extends Activity 
	implements ActionBar.TabListener, OnItemSelectedListener 
{
	View mCustomMenuView; 
	Fragment mFragment;
	private int currentConfMenuSelection = 0;
	private int currentDivMenuSelection = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		//grab the action bar instance for manipulation
		final ActionBar bar = getActionBar();
		//setup custom menu view (spinner)
		mCustomMenuView = getLayoutInflater().inflate(R.layout.custom, null);
		//set the custom menu view into the action bar
		bar.setCustomView(mCustomMenuView,
				new ActionBar.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		//give the spinner menu view 'this' as a click listener
		((Spinner)mCustomMenuView).setOnItemSelectedListener(this);
		
		//add the 3 tabs; league, conference and division
		bar.addTab(bar.newTab().setText("League").setTabListener(this));
		bar.addTab(bar.newTab().setText("Conference").setTabListener(this));
		bar.addTab(bar.newTab().setText("Division").setTabListener(this));
		//ensure that home sends user back to main screen
		bar.setDisplayHomeAsUpEnabled(true);
		//and remove the title no title for home button
		bar.setDisplayShowTitleEnabled(false);
		//set that navigation mode is tabs
		bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		
	}
	
	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {
		//
	}
	
	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		String tag = displayCustomMenu(tab.getPosition());
		
		//the only fragment handled here is the League type, others
		// are handled in the custom menu itemClick.
		if (tag.equals("League")) {
			//call method to add the fragment to the transaction
			this.addFragment(tag, ft);
			//no need to commit the transaction here, the onTabSelected 
			// handles that for us
		}
	}
	
	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
		detachAndDestroyFragment(ft);
	}
	
	private void detachAndDestroyFragment(FragmentTransaction ft) {
		if (mFragment != null) {
			//detach and destroy!!
			ft.detach(mFragment);
			
		}
	}
	
	private void addFragment(String tag, FragmentTransaction ft) {
		Bundle args = new Bundle();
		if (tag.equals("League")) {
			args.putStringArrayList("teamNames", getTeamNames(true, 0, 0));
		} else if (tag.equals("WestConf") || tag.equals("EastConf")) {
			args.putStringArrayList("teamNames", getTeamNames(false, (tag.equals("WestConf")) ? 1 : 2, 0));
		} else {
			args.putStringArrayList("teamNames", getTeamNames(false, 0, new Loader(this).getDivisionFromName(tag)));
		}
		
		ft.disallowAddToBackStack();
		
		mFragment = Fragment.instantiate(this, StandingsListFragment.class.getName(), args);
		Fragment mFragment2 = Fragment.instantiate(this, TeamViewFragment.class.getName(), args);
		
		//add it to the transaction
		ft.add(R.id.standings_list, mFragment, tag);
		ft.add(R.id.team_view, mFragment2, "teamView");
	}
	
	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		String tag = null;
		
		if (parent.getId() == 1) {
			currentConfMenuSelection = position;
			if (((TextView)view).getText().toString().equals("Western")) {
				tag = "WestConf";
			} else {
				tag = "EastConf";
			}
		} else {
			currentDivMenuSelection = position;
			tag = ((TextView)view).getText().toString();
		}
		
		FragmentTransaction ft = this.getFragmentManager().beginTransaction();
		//destroy any existing fragment instance
		this.detachAndDestroyFragment(ft);
		//generate/load the fragment and add to the transaction
		this.addFragment(tag, ft);
		//commit the transaction
		ft.commit();
	}
	
	private ArrayList<String> getTeamNames(boolean isLeague, int conferenceId, int divisionId) {
		Loader ldr = new Loader(this);
		ArrayList<String> teamNames = null;
		
		if (isLeague) {
			Log.d("Standings", "loading All Teams");
			teamNames = ldr.getTeamNames();
		} else {
			if (conferenceId > 0) {
				Log.d("Standings", "loading Conference Teams");
				teamNames = ldr.getTeamNamesByConference(conferenceId);
			} else {
				Log.d("Standings", "loading Division Teams");
				teamNames = ldr.getTeamNames(divisionId);			
			}
		}
		
		return teamNames;	
	}
	
	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		
	}
	
	private String displayCustomMenu(int tabPosition) {
		final ActionBar bar = getActionBar();
		boolean change = false;
		BaseAdapter adapter;
		String rv = null;
		
		switch (tabPosition) {
			case 0:
				rv = "League";
				break;
			case 1:
				adapter = new customMenuAdapter(this, this.getResources().getStringArray(R.array.conference), false);
				((Spinner)mCustomMenuView).setId(1);
			    ((Spinner)mCustomMenuView).setAdapter(adapter);
			    ((Spinner)mCustomMenuView).setSelection(currentConfMenuSelection);
			    change = true;
			    rv = "Conference";
				break;
			case 2:
				ArrayList<String> divs = (new Loader(this)).getDivisionNames();
				String[] divisions = new String[divs.size()];
				divs.toArray(divisions);
				
				adapter = new customMenuAdapter(this, divisions, true);
				((Spinner)mCustomMenuView).setId(2);
				((Spinner)mCustomMenuView).setAdapter(adapter);
				((Spinner)mCustomMenuView).setSelection(currentDivMenuSelection);
			    change = true;
			    rv = "Division";
				break;
		}
		
		bar.setDisplayShowCustomEnabled(change);
		return rv;
	}
	
	public class customMenuAdapter extends BaseAdapter {
		final Context ctx;
		final String[] items;
		final boolean isDivs;
		
		public customMenuAdapter(Context context, String[] itemArray, boolean isDivision) {
		    super();
		    this.isDivs = isDivision;
		    this.items = itemArray;
		    this.ctx = context;
		}
		
		@Override
		public CharSequence getItem(int position) {
			return items[position];
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(android.R.layout.simple_spinner_item, null);
				v.setPadding(5, 5, 5, 5);
			}
			
			((TextView)v).setText(getItem(position));
			
			return v;
		}
		
		@Override
		public int getCount() {
			return items.length;
		}
		
		@Override
		public long getItemId(int position) {
			return position;
		}
	}
	
	
}